<style>
table.lo * { font-size: 12px; font-family: Trebuchet MS; }
.pure_table_list { width: 100%; border: 1px solid #aaa !important; }
.pure_table_list * { font-size: 12px !important; font-family: Trebuchet MS; }
.pure_button_cart { margin-left: 5px; font-weight: bold; font-size: 14px !important; }
div.title { font-weight: bold; font-size: 16px; margin-bottom: 5px; font-family: Lucida Sans Unicode; }
div.total { text-align: right; }
div.total div { border: 1px solid #ddd; background: #fff; padding: 5px 10px; width: 350px; margin: 5px 0 0 auto; font-size: 14px; font-weight: bold; }
div.total span.remind { display: block; color: #777; font-size: 12px; font-weight: normal; }
div.total span.remind a { color: #777; }
.pure_form_extra label, .pure_form_extra input { font-size: 12px !important; }
.pure_form_extra .mandatory { color: #ff0000; padding-left: 5px; }
.pure_form_extra { background: #fff; padding: 10px; border: 1px solid #aaa; border-radius: 8px; }
</style>

<?php
$user = null;
if (isset($_SESSION['user'])) {
  $user = json_decode($_SESSION['user']);
}

$currs = $orm->get('pb_ecom_currency', 't.title', 'ASC', NULL, NULL, NULL)->d;

$cart = array();
if (isset($_SESSION['cart'])) {
  $cart = json_decode($_SESSION['cart']);
}
?>

<table class="lo" cellpadding=0 cellspacing=0>
  <tr>
    <td style="width: 730px; vertical-align: top; padding-right: 10px;">
      <div class="pure-form pure-form-aligned pure_form_extra">
        <div class="title">我的购物车</div>
        <table class="pure-table pure_table_list" cellpadding=0 cellspacing=0>
          <thead>
            <tr>
              <th>商品</th>
              <th style="width: 60px;">单重(kg)</th>
              <th style="width: 80px;">数量</th>
              <th style="width: 60px;">库存</th>
              <th style="width: 60px;">单价</th>
              <th style="width: 90px;">总和</th>
              <th style="width: 40px;">&nbsp;</th>
            </tr>
          </thead>
          <tbody id="cart_body"></tbody>
        </table>
        <div class="total">
          <div>
            <span id="currs">
            <?php foreach ($currs as $itm) { ?>
              <input type="radio" id="curr_<?php echo $itm->title; ?>" onclick="update_curr(<?php echo $itm->id; ?>);" name="curr" /><label for="curr_<?php echo $itm->title; ?>" style="margin-right: -5px !important;"><?php echo $itm->display_name; ?></label>
            <?php } ?>
            </span>
            总和: <span id="cart_total"></span>
            <?php if (!isset($_SESSION['user'])) { ?>
            <span class="remind">没有登录? 赶紧<a href="#" onclick="return Url.redirect(__redmd, __sys + '.php?i=' + __login_id + '&u=' + Utils.encodeURI(((parent != window) ? parent.document.URL : document.URL)));">登录</a> 或者 <a href="#" onclick="return Url.redirect(__redmd, __sys, __login_id, 'u=' + Utils.encodeURI(((parent != window) ? parent.document.URL : document.URL)));"">加入</a>我们，享受会员折扣</span>
            <?php } ?>
          </div>
        </div>
      </div>
      <div>&nbsp;</div>
      <button onclick="Url.redirect(__redmd, __sys + '.php?i=' + __default_id);" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-shopping-cart  fa-lg"></i>&nbsp;继续购物</button>
      <button onclick="empty_cart();" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-times fa-lg"></i>&nbsp;清空购物车</button>
      <button style="float: right;" onclick="checkout(event);" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-check fa-lg"></i>&nbsp;去结账</button>
      <button style="float: right;" onclick="update_cart();" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-cloud-upload fa-lg"></i>&nbsp;更新购物车</button>
    </td>
    <td style="width: 230px; vertical-align: top;"><?php include PLGN_DIR . basename(dirname(__FILE__)) . '/inc.rightbar.php'; ?></td>
  </tr>
</table>
<div>&nbsp;</div>
<div id="dialog_warning" class="pure-form" style="display: none;">
  <div id="warning" style="font-weight: bold; font-size: 14px; color: red;"></div>
</div>

<script type="text/javascript">
  var __user = JSON.parse('<?php echo addslashes(json_encode($user)); ?>');
  var __cart = JSON.parse('<?php echo addslashes(json_encode($cart)); ?>');
  var __currs = JSON.parse('<?php echo addslashes(json_encode($currs)); ?>');
  var __default_id = '<?php echo $app_data->__default_id; ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __login_id = '<?php echo $app_data->__login_id; ?>';
  var __curr;
  
  $(function(){
    Utils.init_ecomm();
    render();
  });

  function render() {
    render_cart();
  };

  function render_cart() {
    $('#cart_body').empty();
    var total = 0;
    var weight = 0;
    for (var idx in __cart) {
      var itm = __cart[idx];
      itm.__fp = Utils.get_price(__currs, itm.curr, __curr.title, itm.price, itm.__enabled_member == 1 ? (__user ? __user.__discount : null) : null);
      itm.total = itm.__fp * itm.quantity;
      total += itm.total;
      weight += itm.weight * itm.quantity;
      $('#cart_body').append(
        '<tr class="' + ((idx % 2 ==0) ? 'pure-table-even' : 'pure-table-odd') + '">' +
          '<td>' + itm.name + ((itm.attr_opt_code != '') ? ' (' + itm.attr_opt_code + ')' : '') + '</td>' +
          '<td>' + accounting.formatNumber(itm.weight)+ '</td>' +
          '<td><input onchange="update_quantity(event);" class="qty" type="text" id="' + itm.product_id + '_' + itm.attr_opt_id + '" value="' + itm.quantity + '"></input></td>' +
          '<td>' + ((itm.__enabled_stock == 1) ? itm.__stock : '无限量') + '</td>' +
          '<td>' + accounting.formatMoney(itm.__fp, __curr.dollar_symbol) + '</td>' +
          '<td>' + accounting.formatMoney(itm.total, __curr.dollar_symbol) + '</td>' +
          '<td><i style="cursor: pointer;" class="fa fa-times" onclick="delete_purchase(\'' + itm.product_id + '_' + itm.attr_opt_id + '\')"></i></td>' +
        '</tr>'
      );
    }

    $('#cart_total').html(accounting.formatMoney(total, __curr.dollar_symbol) + ' (' + weight + 'kg)');
    
    if (__cart.length == 0) {
      $('#cart_body').append('<tr class="roweven"><td colSpan="7">您的购物车为空</td></tr>')
    } else {
      var MIN = 1;
      $('.qty').spinner({ min: MIN });
      $('.qty').on('keyup', function(e) {
        var v = parseInt($(this).val());
        if (isNaN(v)) {
          return $(this).val(MIN);
        }
        if ($(this).val() < MIN) {
           $(this).val(MIN);
        } else {
          $(this).val(v);
        }
        update_quantity(e);
      });
      $('.qty').on('spinchange', function(event, ui) { update_quantity(event); } );
      $('.ui-spinner-button').click(function() {
        $(this).siblings('input').change();
      });
    }
  };

  function update_curr(id) {
    __curr = Utils.get_by_id(id, __currs);
    Cookie.set_cookie('curr', JSON.stringify(__curr), 1);
    render_cart();
  };

  function empty_cart() {
    __cart = []; 
    Ajax.request(
      __requrl.replace('index_cart', 'index') + 'update_cart',
      'req=' + Utils.encodeURI(JSON.stringify(__cart)),
      function(rslt) {
        Utils.set_cartnum(__cart);
        render_cart();
      },
      null
    );
  };

  function update_quantity(ev) {
    var rslt = ev.target.id.split('_');
    for (var idx in __cart) {
      var itm = __cart[idx];
      if (itm.product_id == rslt[0] && itm.attr_opt_id == rslt[1]) {
        itm.quantity = ev.target.value;
        if (itm.__enabled_stock == 1) {
          itm.quantity = Math.min(ev.target.value, itm.__stock);
        }
        itm.total = itm.price * itm.quantity;
        render_cart();
      }
    }
  };

  function delete_purchase(str) {
    var rslt = str.split('_');
    for (var idx in __cart) {
      var itm = __cart[idx];
      if (itm.product_id == rslt[0] && itm.attr_opt_id == rslt[1]) {
        __cart.splice(idx, 1);
      }
    }
    Ajax.request(
      __requrl.replace('index_cart', 'index') + 'update_cart',
      'req=' + Utils.encodeURI(JSON.stringify(__cart)),
      function(rslt) {
        Utils.set_cartnum(__cart);
        render_cart();
      },
      { confirm: 1, tt: '确认', txt: '确认删除么？' }
    );
  };

  function checkout(ev) {
    if (__cart.length == 0) {
      $('#warning').html('您的购物车为空');
      $('#dialog_warning').dialog({
        position: {
          my: 'left+0 bottom+0',
          of: ev.target
        },
        buttons: {
          '关闭': function() { 
            $(this).dialog('close');
          }
        }
      });
      return;
    }
    Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=index_login');
  };

  function update_cart() {
    Ajax.request(
      __requrl.replace('index_cart', 'index') + 'update_cart',
      'req=' + Utils.encodeURI(JSON.stringify(__cart)),
      function(rslt) {
        Utils.set_cartnum(__cart);
      },
      null
    );
  };
</script>
